package com.wind.test;

import com.wind.entity.Cache;
import org.hibernate.ejb.QueryHints;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import javax.persistence.*;

public class JpaTest06_JPQL_查询缓存 {

  private EntityManagerFactory entityManagerFactory;
  private EntityManager entityManager;
  private EntityTransaction entityTransaction;

  @Before
  public void init() {
    entityManagerFactory = Persistence.createEntityManagerFactory("JpaDemo");
    entityManager = entityManagerFactory.createEntityManager();
    entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();
  }

  @After
  public void destory() {
    entityTransaction.commit();
    entityManager.close();
    entityManagerFactory.close();
  }

  // 没设置查询缓存 执行同一查询 SQL 会发送两次查询 SQL
  @Test
  public void testQueryCacheNotOpen() {
    Query query = entityManager.createNamedQuery("CacheQuery").setParameter(new Integer(1), 1);

    Cache cache1 = (Cache) query.getSingleResult();
    System.out.println(cache1);
    Cache cache2 = (Cache) query.getSingleResult();
    System.out.println(cache2);
    // 执行结果 发送了两次 SQL
  }

  /*
    开启查询缓存的条件：
      1）在 persistence.xml 文件中，配置开启了 二级缓存（<property name="hibernate.cache.use_query_cache" value="true"/>）
      2）在 Query 上设置 .setHint(QueryHints.HINT_CACHEABLE, true)
   */
  @Test
  public void testQueryCache() {
    Query query = entityManager.createNamedQuery("CacheQuery").setParameter(new Integer(1), 1);
    query.setHint(QueryHints.HINT_CACHEABLE, true); // 开启查询缓存

    Cache cache1 = (Cache) query.getSingleResult();
    System.out.println(cache1);
    Cache cache2 = (Cache) query.getSingleResult();
    System.out.println(cache2);
    // 执行结果 发送了一次 SQL
  }

}
